local blaze = require "blaze"
local app = require "app"
local gamelib = require "club.threecard.gamelib"
local Chatter = require "club.threecard.gamelib.widgets.Chatter"
local AvatarIcon = require "ui.Common.AvatarIcon"
local chat = gamelib.chat

local log = blaze.logging.get("Seat")

local M = app.ui.element()

local function update(self)
    if self.player then
        self.invite_btn.gameObject:SetActive(false)
        self.player_obj:SetActive(true)
        self.name_txt.text = self.player.name
        self.avatar_icon:set_player(self.player)
        self.chip_txt.text = app.i18n.number(self.player.chip, "chip3")
    else
        self.invite_btn.gameObject:SetActive(true)
        self.player_obj:SetActive(false)
    end
end

local function tick(self)
    while true do
        self.app.coroutine.wait(1)
        if self.player then
            self.chip_txt.text = app.i18n.number(self.player.chip, "chip3")
        end
    end
end

function M:ctor()
    self.avatar_icon = AvatarIcon.new()
    self.chatter = Chatter.new()
end

function M:on_load()
    self:super("on_load")
    self.avatar_icon:load()
    self:start_coroutine(tick, self)
end

function M:on_injected(bind)
    bind("gameobject.element", self.icon_obj, self.avatar_icon)
    bind("gameobject.element", self.chatter_obj, self.chatter)
    bind("button.click", self.invite_btn, self.on_invite)
    bind("button.click", self.icon_btn, self.on_detail)
    update(self)
end

function M:on_invite()
    log.info("邀请玩家")
end

function M:on_detail()
    log.info("查看玩家")
end

function M:set_player(player)
    self.player = player
    self:lazy("on_set_player")
end

function M:clear_player(player)
    self.player = nil
    self:lazy("on_clear_player")
end

function M:play_payout_fx(payout)
    if not self.loaded then
        return
    end
    if not self.payout_fx then
        local PayoutFX = require "club.threecard.slotlib.widget.PayoutFX"
        self.payout_fx = PayoutFX.new()
        self.payout_fx:set_parent(self.transform)
    end
    self.payout_fx:play(payout)
end

function M:on_set_player()
    update(self)
end

function M:on_clear_player()
    update(self)
end

function M:on_release()
    self:super("on_release")
    self.avatar_icon:release()
    self.chatter:release()
end

return M